/**
 * Copyright (c) 2012-2013 Nokia Corporation. All rights reserved.
 * Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation.
 * Oracle and Java are trademarks or registered trademarks of Oracle and/or its
 * affiliates. Other product and company names mentioned herein may be trademarks
 * or trade names of their respective owners.
 * See LICENSE.TXT for license information.
 */

package com.nokia.example.amaze;

import javax.microedition.io.ConnectionNotFoundException;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Image;
import javax.microedition.midlet.MIDlet;

import com.nokia.example.amaze.ui.MazeCanvas;
import com.nokia.mid.ui.VirtualKeyboard;

/**
 * Main class defining the MIDlet.
 */
public class Main
      extends MIDlet
      implements SplashScreen.Listener
{
    // Constants
    public static final boolean HAS_ONE_KEY_BACK;
    private static final int SPLASH_SCREEN_BG_COLOR = 0xff00b4ec;
    private static final String SPLASH_SCREEN_IMAGE =
            "/graphics/splash-screen-image.png";
    private static final int SPLASH_SCREEN_DELAY = 3000; // Milliseconds

    // Members
    private static Main _instance = null;
    private SplashScreen _splashScreen = null;
    private MazeCanvas _mazeCanvas = null;

    /**
     * Static constructor.
     */
    static {
        String keyboardType = System.getProperty("com.nokia.keyboard.type");
        
        if (keyboardType  != null && keyboardType.equalsIgnoreCase("OnekeyBack")) {
            HAS_ONE_KEY_BACK = true;
        }
        else {
            HAS_ONE_KEY_BACK = false;
        }
    }

    /**
     * Constructor.
     */
    public Main() {
        _instance = this;
        
        // Hide the command for opening the virtual keypad
        try {
            Class.forName("com.nokia.mid.ui.VirtualKeyboard");
            VirtualKeyboard.hideOpenKeypadCommand(true);
        }
        catch (ClassNotFoundException e) {}
        
        _splashScreen = new SplashScreen(this, SPLASH_SCREEN_BG_COLOR);
        _splashScreen.loadImage(SPLASH_SCREEN_IMAGE);
    }

    /**
     * From MIDlet.
     */
    public void startApp() {
        final Display display = Display.getDisplay(this);
        Displayable current = display.getCurrent();
        
        if (current == null) {
            // Check that the API is available
            boolean isApiAvailable =
                    (System.getProperty("microedition.m3g.version") != null);
            
            if (!isApiAvailable) {
                quitApp();
            }
            else {
                _mazeCanvas = new MazeCanvas(this);
                
                if (_splashScreen != null) {
                    _splashScreen.show(display, _mazeCanvas, SPLASH_SCREEN_DELAY);
                    _mazeCanvas.init();
                }
                else {
                    _mazeCanvas.init();
                    display.setCurrent(_mazeCanvas);
                }
            }
        }
        else {
            // In case the MIDlet has been hidden
            if (current == _mazeCanvas) {
                _mazeCanvas.setRunning(true);
            }
            
            Display.getDisplay(this).setCurrent(current);
        }
    }

    /**
     * From MIDlet.
     */
    public void pauseApp() {
        _mazeCanvas.pause();
        _mazeCanvas.setRunning(false);
    }

    /**
     * From MIDlet.
     */
    public void destroyApp(boolean unconditional) {
        _mazeCanvas.setRunning(false);
    }


    /**
     * From SplashScreen.Listener.
     */
    public void onFinished() {
        // Splash screen is no longer required
        _splashScreen = null;
    }

    /** 
     * Quits the app but first stops the game thread.
     */
    public void quitApp() {
        _mazeCanvas.setRunning(false);
        notifyDestroyed();
    }

    /**
     * Loads the given image by filename.
     * @param filename The path of the image file.
     * @return The created image or null in case of a failure.
     */
    public static Image makeImage(String filename) {
        Image image = null;
        
        try {
            image = Image.createImage(filename);
        }
        catch (Exception e) {
            // Use a null image instead
            System.out.println("Failed to create image: " + filename);
        }
        
        return image;
    }

    /**
     * Tries to open the given URL. If successful, this app is be terminated.
     * @param url The URL to open.
     */
    public static void openLink(String url) {
        System.out.println("Main.openLink(): " + url);
        
        try {
            if (_instance.platformRequest(url)) {
                _instance.quitApp();
            }
        }
        catch (ConnectionNotFoundException e) {
            System.out.println("Main.openLink(): " + e.toString());
        }
        catch (Exception e) {}
    }
}
